﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hyt.Core.Authentication
{
    public class AuthManager : IAuthManager
    {
        private readonly List<IAuthRule> _rules;

        public AuthManager()
        {
            _rules=new List<IAuthRule>();
        }

        public void AddRule(IAuthRule rule)
        {
            if (!_rules.Contains(rule))
            {
                _rules.Add(rule);
            }
        }

        public void RemoveRule(IAuthRule rule)
        {
            if (_rules.Contains(rule))
            {
                _rules.Remove(rule);
            }
        }

        public AuthResult Check(Security.IPrincipal principal, string operation)
        {
            foreach (var rule in _rules)
            {
                var result = rule.Match(principal, operation);
                if (result.Status == RuleMatchState.None) continue;
                return result.Status == RuleMatchState.Allow ? new AuthResult {Status = true, Message = result.Message} : new AuthResult { Status = false, Message = result.Message };
            }
            return new AuthResult { Status = false};
        }
    }
}
